import { Injectable } from '@nestjs/common';
import { CreateTemplateDto } from './dto/create-template.dto';
import { UpdateTemplateDto } from './dto/update-template.dto';

import { QueryDto } from './dto/query.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Template } from './entities/template.entity';

import { Like, Raw, Repository } from 'typeorm';

@Injectable()
export class TemplateService {
  constructor(
    @InjectRepository(Template)
    private readonly templateRepository: Repository<Template>,
  ) {}

  async create(createTemplateDto: CreateTemplateDto) {
    const exit = await this.templateRepository.findOneBy({
      name: createTemplateDto.name,
    });

    if (exit) {
      return {
        code: 400,
        data: null,
        message: 'template已存在',
      };
    }

    const template = this.templateRepository.create(createTemplateDto);
    const savedTemplate = await this.templateRepository.save(template);
    return {
      code: 200,
      data: {
        id: savedTemplate.id,
        name: savedTemplate.name,
        type: savedTemplate.type,
        description: savedTemplate.description,
        createdAt: savedTemplate.createdAt,
      },
      message: '创建成功',
    };
  }

  async findAll(query: QueryDto) {
    const { pageNum = 1, pageSize = 10, keywords = '', ...rest } = query;
    const [result, total] = await this.templateRepository.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      where: {
        ...rest,
        deleted: false,
        name: keywords
          ? Raw(
              (alias) =>
                `${alias} REGEXP :pattern OR description REGEXP :pattern`,
              { pattern: keywords.replace(/,/g, '|') },
            )
          : Like('%'),
      },
    });

    return {
      rows: result,
      total,
    };
  }

  findOne(id: number) {
    return this.templateRepository.findOne({
      where: {
        id,
      },
    });
  }

  async update(id: number, updateTemplateDto: UpdateTemplateDto) {
    return await this.templateRepository.update(id, updateTemplateDto);
  }

  remove(id: number) {
    return this.templateRepository.delete(id);
  }
}
